<template>
  <div class="post-detail-view">
    <div class="detail-header">
      <el-button @click="emits('back')" class="back-button">
        <el-icon><ArrowLeft /></el-icon>
        返回讨论区
      </el-button>
    </div>

    <el-card v-if="post" class="detail-card">
      <!-- 帖子头部 -->
      <div class="post-detail-header">
        <div class="post-header-main">
          <div class="author-info">
            <div class="author-meta">
              <span class="author-name">{{ post.user && post.user.username }}</span>
              <span class="post-time">
                <el-icon><Clock /></el-icon>
                {{ formatTime(post.created_at) }}
              </span>
            </div>
          </div>
          <el-tag
            size="large"
            :type="getTagType(post.topic)"
            class="topic-tag"
            effect="light"
          >
            {{ post.topic }}
          </el-tag>
        </div>
      </div>

      <!-- 帖子内容 -->
      <div class="post-detail-content content-wrapper" v-html="post.content"></div>

      <!-- 帖子底部操作栏 -->
      <div class="post-detail-footer">
        <div class="post-actions">
      <!-- 添加关注按钮 -->
      <el-button
        v-if="post && post.user && post.user.id !== currentUser.id"
        type="text"
        class="action-btn follow-btn"
        :class="{ 'is-following': isUserFollowed }"
        @click="handleFollowUser"
      >
        <el-icon><User /></el-icon>
        {{ isUserFollowed ? '已关注' : '关注' }}
      </el-button>
         <el-button
             type="text"
             class="action-btn favorite-btn"
             :class="{ 'is-favorited': post.is_favorite }"
              @click.stop="handleFavorite(post)"
         >
         <el-icon><Star /></el-icon>
             收藏
         </el-button>
          <el-button
            type="text"
            class="action-btn like-btn"
            :class="{ 'is-liked': post.is_liked }"
            @click="handlePostLike"
          >
           <el-icon><Thumb /></el-icon>
             {{ post.likes_count }} 赞
           </el-button>
        </div>
      </div>

      <!-- 评论区 -->
      <div class="comments-section">
        <h3 class="section-title">
          <el-icon><ChatRound /></el-icon>
          评论区
        </h3>

        <!-- 评论输入框 -->
        <div class="comment-form">
          <div class="mention-wrapper">
            <el-input
              v-model="commentContent"
              type="textarea"
              :rows="3"
              placeholder="写下你的评论..."
              class="comment-input"
              @keyup.enter.prevent
              @input="handleCommentInput"
              ref="commentInput"
            />
            <!-- @提及用户的建议框 -->
            <div
              v-if="showMentionSuggestions"
              class="mention-suggestions"
              :style="mentionPosition"
            >
              <div
                v-for="user in mentionSuggestions"
                :key="user.id"
                class="mention-item"
                @click="selectMention(user)"
                :class="{ 'active': selectedMentionIndex === mentionSuggestions.indexOf(user) }"
              >
                <el-avatar :size="28" class="mention-avatar">
                  {{ user.username.charAt(0).toUpperCase() }}
                </el-avatar>
                <span class="mention-name">{{ user.username }}</span>
                <span class="mention-id">({{ user.id }})</span>
              </div>
              <div v-if="mentionSuggestions.length === 0" class="no-suggestions">
                无匹配用户
              </div>
            </div>
          </div>
          <div class="comment-form-footer">
            <el-button type="primary" @click="submitComment" class="submit-btn">
              发表评论
            </el-button>
          </div>
        </div>

        <!-- 评论列表 -->
        <div class="comments-list">
          <el-empty
            v-if="!post.comments || post.comments.length === 0"
            description="暂无评论"
            class="empty-state"
          />
          <template v-else>
            <div
              v-for="comment in post.comments"
              :key="comment.id"
              class="comment-item"
            >
              <div class="comment-header">
                  <div class="comment-meta">
                    <span class="commenter-name">{{ comment.user && comment.user.username }}</span>
                    <span class="comment-time">{{ formatTime(comment.created_at) }}</span>
                  </div>
                <el-button
                  v-if="canDeleteComment(comment)"
                  type="text"
                  @click="handleDeleteComment(comment.id)"
                  class="delete-btn"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
              <div class="comment-content" v-html="comment.content"></div>
              <div class="comment-footer">
                <el-button
                  type="text"
                  class="like-btn"
                  :class="{ 'is-liked': comment.is_liked }"
                  @click="handleCommentLike(comment)"
                >
                <el-icon><Thumb /></el-icon>
                  {{ comment.likes_count }} 赞
                </el-button>
              </div>
            </div>
          </template>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {ArrowLeft, Thumb, Star, Clock, ChatRound, Delete, User} from '@element-plus/icons-vue'
import axios from 'axios'
import debounce from 'lodash/debounce'

const props = defineProps({
  post: {
    type: Object,
    required: true
  },
  currentUser: {
    type: Object,
    required: true
  },
  isTeacher: {
    type: Boolean,
    required: true
  }
})

const emits = defineEmits(['back', 'update:post'])
// 获取标签类型
const getTagType = (topic) => {
  const types = {
    '问题': 'danger',
    '分享': 'success',
    '讨论': 'warning',
    '建议': 'info'
  }
  return types[topic] || 'info'
}

// 关注状态的响应式引用
const isUserFollowed = ref(false)
const followingList = ref([])
// 评论相关的响应式变量
const comments = ref([])
const isLoadingComments = ref(false)
const commentContent = ref('') // 评论内容
const mentionSuggestions = ref([]) // @用户建议列表
const showMentionSuggestions = ref(false) // 是否显示@建议框
const currentMentionSearch = ref('') // 当前@搜索的内容
const selectedMentionIndex = ref(-1) // 当前选中的@建议索引
const commentInput = ref(null) // 评论输入框的引用
const mentionedUsers = ref([]) // 已@的用户列表
const mentionPosition = ref({  // 响应式变量用于计算位置
  position: 'absolute',
  left: '0px',
  top: '0px'
})

// 获取关注数据
const fetchFollowData = async () => {
  try {
    const response = await axios.get('/backend/api/account/follow_data/', {
      withCredentials: true
    })

    if (response.data && response.data.following) {
      followingList.value = response.data.following
      // 检查当前帖子作者是否在关注列表中
      if (props.post && props.post.user && props.post.user.id) {
        isUserFollowed.value = followingList.value.includes(props.post.user.id)
      }
    }
  } catch (error) {
    console.error('获取关注数据失败:', error)
  }
}

// 处理关注/取消关注用户
const handleFollowUser = async () => {
  if (!props.post || !props.post.user || !props.post.user.id || props.post.user.id === props.currentUser.id) return

  try {
    const endpoint = isUserFollowed.value ? 'unfollow' : 'follow'
    const response = await axios.post(
      `/backend/api/account/${endpoint}/`,
      {
        user_id: props.post.user.id
      },
      { withCredentials: true }
    )

    if (response.data.message) {
      // 更新关注状态
      isUserFollowed.value = !isUserFollowed.value

      // 显示操作成功消息
      ElMessage({
        type: 'success',
        message: isUserFollowed.value ? '关注成功' : '已取消关注',
        duration: 1500
      })

      // 重新获取关注数据以保持同步
      await fetchFollowData()
    }
  } catch (error) {
    console.error('关注操作失败:', error)
    let errorMessage = '操作失败，请稍后重试'
    if (error.response && error.response.data && error.response.data.error) {
      errorMessage = error.response.data.error
    }
    ElMessage.error(errorMessage)
  }
}

//收藏帖子
const handleFavorite = async (post) => {
  try {
    const endpoint = post.is_favorite ? 'unfavorite' : 'favorite'
    const response = await axios.post(
      `/backend/api/post/${post.id}/${endpoint}/`,
      {},
      { withCredentials: true }
    )

    if (response.data.message) {
      // 更新帖子的收藏状态
      post.is_favorite = !post.is_favorite

      ElMessage({
        type: 'success',
        message: post.is_favorite ? '收藏成功' : '取消收藏成功',
        duration: 1500
      })
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    let errorMessage = '操作失败，请稍后重试'
    if (error.response && error.response.data && error.response.data.error) {
      errorMessage = error.response.data.error
    }
    ElMessage.error(errorMessage)
  }
}

// 帖子点赞/取消点赞
const handlePostLike = async () => {
  try {
    const endpoint = props.post.is_liked ? 'unlike' : 'like'
    const response = await axios.post(
      `/backend/api/post/${props.post.id}/${endpoint}/`,
      {},
      { withCredentials: true }
    )

    if (response.data.success) {
      // 更新帖子点赞状态
      props.post.likes_count = response.data.likes
      props.post.is_liked = !props.post.is_liked

      // 发出更新事件
      emits('update:post', props.post)

      // 显示操作成功消息
      ElMessage({
        type: 'success',
        message: props.post.is_liked ? '点赞成功' : '取消点赞成功',
        duration: 1500
      })
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}
// 获取评论列表
const fetchComments = async () => {
  if (!props.post || !props.post.id) return

  isLoadingComments.value = true
  try {
    const response = await axios.get(`/backend/api/post/${props.post.id}/comments/`, {
      withCredentials: true
    })
    comments.value = response.data
    // 更新post对象中的comments
    props.post.comments = response.data
  } catch (error) {
    console.error('获取评论列表失败:', error)
    ElMessage.error('获取评论列表失败')
  } finally {
    isLoadingComments.value = false
  }
}

/**
 * 防抖处理的用户搜索函数
 * 根据学号前缀搜索用户
 */
const searchUsers = debounce(async (query) => {
  if (!query) {
    mentionSuggestions.value = []
    return
  }

  try {
    const response = await axios.get('/backend/api/post/students/search/', {
      params: { id: query },
      withCredentials: true
    })
    mentionSuggestions.value = response.data
  } catch (error) {
    console.error('搜索用户失败:', error)
    mentionSuggestions.value = []
  }
}, 300) // 300ms的防抖延迟

/**
 * 处理评论输入，检测@符号并触发用户搜索
 */
const handleCommentInput = async (value) => {
  const textarea = commentInput.value.$el.querySelector('textarea')
  // 获取当前光标位置
  const cursorPosition = commentInput.value.$el.querySelector('textarea').selectionStart
  const textBeforeCursor = value.substring(0, cursorPosition)
  // 匹配@后面的内容
  const mentionMatch = textBeforeCursor.match(/@(\w*)$/)

  if (mentionMatch) {
    currentMentionSearch.value = mentionMatch[1]
    showMentionSuggestions.value = true
    selectedMentionIndex.value = -1
    await searchUsers(currentMentionSearch.value)

    // 计算@符号的位置
    const textBeforeMention = textBeforeCursor.substring(0, mentionMatch.index)
    const tempElement = document.createElement('div')
    tempElement.style.cssText = window.getComputedStyle(textarea).cssText
    tempElement.style.height = 'auto'
    tempElement.style.position = 'absolute'
    tempElement.style.visibility = 'hidden'
    tempElement.style.whiteSpace = 'pre-wrap'
    tempElement.textContent = textBeforeMention

    document.body.appendChild(tempElement)
    const lines = textBeforeMention.split('\n')
    const currentLineIndex = lines.length - 1
    const lastLine = lines[currentLineIndex]

    // 计算垂直偏移
    const lineHeight = parseFloat(window.getComputedStyle(textarea).lineHeight)
    const verticalOffset = currentLineIndex * lineHeight

    // 计算水平偏移
    const textWidth = tempElement.clientWidth
    document.body.removeChild(tempElement)

    // 更新提示框位置
    mentionPosition.value = {
      position: 'absolute',
      left: `${textWidth}px`,
      top: `${verticalOffset + lineHeight + 5}px`
    }
  } else {
    showMentionSuggestions.value = false
    currentMentionSearch.value = ''
  }
}


/**
 * 选择要@的用户
 */
const selectMention = (user) => {
  const textarea = commentInput.value.$el.querySelector('textarea')
  const cursorPosition = textarea.selectionStart
  // 替换@及其后面的搜索文本
  const textBeforeMention = commentContent.value.substring(0, cursorPosition).replace(/@\w*$/, '')
  const textAfterMention = commentContent.value.substring(cursorPosition)

  // 插入完整的@用户名
  commentContent.value = `${textBeforeMention}@${user.username} ${textAfterMention}`

  // 添加到已@用户列表（避免重复）
  if (!mentionedUsers.value.find(u => u.id === user.id)) {
    mentionedUsers.value.push(user)
  }

  showMentionSuggestions.value = false

  // 设置光标位置到插入的@用户名后面
  nextTick(() => {
    const newPosition = `${textBeforeMention}@${user.username} `.length
    textarea.setSelectionRange(newPosition, newPosition)
    textarea.focus()
  })
}

/**
 * 处理@用户选择时的键盘操作
 */
const handleKeydown = (e) => {
  if (!showMentionSuggestions.value) return

  switch (e.key) {
    case 'ArrowDown': // 向下选择
      e.preventDefault()
      selectedMentionIndex.value = Math.min(
        selectedMentionIndex.value + 1,
        mentionSuggestions.value.length - 1
      )
      break
    case 'ArrowUp': // 向上选择
      e.preventDefault()
      selectedMentionIndex.value = Math.max(selectedMentionIndex.value - 1, 0)
      break
    case 'Enter': // 确认选择
      e.preventDefault()
      if (selectedMentionIndex.value >= 0) {
        selectMention(mentionSuggestions.value[selectedMentionIndex.value])
      }
      break
    case 'Escape': // 关闭建议框
      showMentionSuggestions.value = false
      break
  }
}

/**
 * 提交评论
 */
const submitComment = async () => {
  if (!props.post || !props.post.id) {
    ElMessage.error('帖子信息无效')
    return
  }

  if (!commentContent.value || !commentContent.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
   const mentionedUserIds = JSON.stringify(mentionedUsers.value.map(user => user.id))

  try {
    const response = await axios.post('/backend/api/post/comments/create/', {
      post_id: props.post.id,
      content: commentContent.value,
      mentioned_users: mentionedUserIds  // 发送已@用户的ID列表
    }, {
      withCredentials: true
    })

    // 初始化评论数组（如果不存在）
    if (!props.post.comments) {
      props.post.comments = []
    }
    // 更新评论列表
    await fetchComments()
    // 清空评论框和@用户列表
    commentContent.value = ''
    mentionedUsers.value = []
    ElMessage.success('评论发表成功')
  } catch (error) {
    console.error('发表评论失败:', error)
    ElMessage.error('发表评论失败')
  }
}

// 组件挂载时添加键盘事件监听
onMounted(() => {
   fetchComments()
   fetchFollowData() // 添加获取关注数据
  document.addEventListener('keydown', handleKeydown)
})

// 组件卸载时移除键盘事件监听
onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})

// 删除评论
const handleDeleteComment = async (commentId) => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await axios.delete(`/backend/api/post/comments/${commentId}/delete/`, {
      withCredentials: true
    })

    // 重新获取评论列表
    await fetchComments()
    ElMessage.success('评论删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除评论失败:', error)
      ElMessage.error('删除评论失败')
    }
  }
}

// 评论点赞/取消点赞
const handleCommentLike = async (comment) => {
  try {
    const endpoint = comment.is_liked ? 'unlike' : 'like'
    const response = await axios.post(
      `/backend/api/post/comments/${comment.id}/${endpoint}/`,
      {},
      { withCredentials: true }
    )

    if (response.data.success) {
      comment.likes_count = response.data.likes
      comment.is_liked = !comment.is_liked

      ElMessage({
        type: 'success',
        message: comment.is_liked ? '点赞成功' : '取消点赞成功',
        duration: 1500
      })
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 检查是否可以删除评论
const canDeleteComment = (comment) => {
  if (!comment || !comment.user) return false
  return props.isTeacher || comment.user.id === props.currentUser.id
}

// 格式化时间
const formatTime = (timeStr) => {
  const date = new Date(timeStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

</script>

<style scoped>
.post-detail-view {
  max-width: 1000px;
  margin: 0 auto;
  padding: 24px;
}

.detail-header {
  margin-bottom: 24px;
}

.back-button {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.back-button:hover {
  transform: translateX(-4px);
}

.detail-card {
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  background: #fff;
}

.post-header-main {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid #f0f2f5;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.author-avatar {
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.author-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.author-name {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.post-time {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
  color: #909399;
}

.topic-tag {
  padding: 8px 16px;
  font-weight: 500;
  border-radius: 6px;
}

.content-wrapper {
  padding: 32px 0;
  font-size: 16px;
  line-height: 1.8;
  color: #2c3e50;
}

.content-wrapper :deep(h1),
.content-wrapper :deep(h2),
.content-wrapper :deep(h3) {
  margin: 24px 0 16px;
  font-weight: 600;
  color: #2c3e50;
}

.content-wrapper :deep(p) {
  margin: 16px 0;
  line-height: 1.8;
}

.content-wrapper :deep(img) {
  max-width: 100%;
  border-radius: 8px;
  margin: 16px 0;
}

.post-detail-footer {
  padding: 16px 0;
  border-top: 1px solid #f0f2f5;
}

.post-actions {
  display: flex;
  gap: 20px;
  justify-content: flex-end;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  font-size: 14px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.action-btn:hover {
  background-color: #f5f7fa;
}

.like-btn.is-liked {
  color: #409EFF;
}

.like-count {
  margin-left: 4px;
}

/* 评论区样式 */
.comments-section {
  margin-top: 40px;
  padding-top: 24px;
  border-top: 2px solid #f0f2f5;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 24px;
}

.comment-form {
  margin-bottom: 32px;
}

.comment-input {
  margin-bottom: 16px;
}

.mention-wrapper {
  position: relative;
}

.mention-suggestions {
  position: absolute;
  z-index: 1000;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  max-height: 240px;
  overflow-y: auto;
  width: 240px;
}

.mention-item {
  padding: 10px 16px;
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.mention-item:hover,
.mention-item.active {
  background-color: #f5f7fa;
}

.mention-avatar {
  border: 1px solid #eee;
}

.mention-name {
  font-weight: 500;
  color: #2c3e50;
}

.mention-id {
  color: #909399;
  font-size: 13px;
}

.no-suggestions {
  padding: 12px;
  text-align: center;
  color: #909399;
}

.comments-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.comment-item {
  padding: 20px;
  border-radius: 12px;
  background-color: #f8f9fa;
  transition: all 0.3s ease;
}

.comment-item:hover {
  background-color: #f0f2f5;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.commenter-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.commenter-avatar {
  border: 2px solid #fff;
}

.commenter-name {
  font-weight: 500;
  color: #2c3e50;
}

.comment-time {
  font-size: 13px;
  color: #909399;
}

.comment-content {
  padding: 8px 0;
  font-size: 15px;
  line-height: 1.6;
  color: #2c3e50;
}

.delete-btn {
  color: #f56c6c;
  opacity: 0;
  transition: all 0.3s ease;
}

.comment-item:hover .delete-btn {
  opacity: 1;
}

.empty-state {
  padding: 48px;
  background: #f8f9fa;
  border-radius: 12px;
}

/* 评论列表动画 */
.comment-list-enter-active,
.comment-list-leave-active {
  transition: all 0.3s ease;
}

.comment-list-enter-from,
.comment-list-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .post-detail-view {
    padding: 16px;
  }

  .post-header-main {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .topic-tag {
    align-self: flex-start;
  }

  .comment-item {
    padding: 16px;
  }
}
/*关注*/
.follow-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  font-size: 14px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.follow-btn.is-following {
  color: #409EFF;
}

.follow-btn:hover:not(.is-following) {
  background-color: #f5f7fa;
}

.follow-btn.is-following:hover {
  color: #f56c6c;
}

.follow-btn.is-following:hover::after {
  content: '取消关注';
}

.follow-btn.is-following:hover .el-icon,
.follow-btn.is-following:hover span {
  display: none;
}

/*收藏按钮*/

.favorite-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
}

.favorite-btn.is-favorited {
  color: #f7ba2a;
}

.favorite-btn.is-favorited .el-icon {
  fill: currentColor;
}

.favorite-btn:hover {
  background-color: #f5f7fa;
}
</style>